<?php
class AccountPayableSearch extends CFormModel {
	public $payDateMin;
	public $payDateMax;
	public $keyword;
	public $keywordRange;
	public $priceMin;
	public $priceMax;
	public $projectId;

	public static function getKeywordRanges() {
		return array(
			'1' => '摘要',
			'2' => '商家名',
			'3' => '付款对象',
			'4' => '票据付款对象',
			'5' => '备注'
		);
	}

	public function rules() {
		return array(
			array(
				'projectId',
				'numerical',
				'integerOnly' => true,
			),
			array(
				'priceMin, priceMax',
				'numerical',
			),
			array(
				'payDateMin, payDateMax',
				'date',
				'format' => 'yyyy-MM-dd',
			),
			array(
				'keyword',
				'length',
				'max' => 255
			),
			array(
				'keywordRange',
				'type',
				'type' => 'array'
			),
		);
	}

	public function attributeLabels() {
		return array(
			'priceMin' => '付款金额',
			'keyword' => '关键词',
			'projectId' => '项目',
			'payDateMin' => '付款时间'
		);
	}

	/**
	 * @return CDbCriteria
	 */
	public function createCriteria($tableAlias, $fast = false) {
		$criteria = new CDbCriteria;
		if (!$fast) {
			$criteria->with = array(
				'merchant',
				'project'
			);
		}
		if ($this->keyword) {
			$keywordCriteria = new CDbCriteria();
			foreach ($this->keywordRange as $range) {
				switch ($range) {
				case '1':
					$keywordCriteria->addSearchCondition($tableAlias.'.summary', $this->keyword, true, 'OR');
					break;
				case '2':
					if ($fast) {
						$criteria->join = 'LEFT JOIN {{merchant}} merchant on merchant.id=merchantId';
					}
					$keywordCriteria
						->addSearchCondition('merchant.name', $this->keyword, true, 'OR');
					$keywordCriteria
						->addSearchCondition('merchant.otherName', $this->keyword, true, 'OR');
					break;
				case '3':
					$keywordCriteria->addSearchCondition($tableAlias.'.payee', $this->keyword, true, 'OR');
					break;
				case '4':
					$keywordCriteria->addSearchCondition($tableAlias.'.ticketPayee', $this->keyword, true, 'OR');
					break;
				case '5':
					$keywordCriteria->addSearchCondition($tableAlias.'.note', $this->keyword, true, 'OR');
					break;
				default:
					break;
				}
			}
			$criteria->mergeWith($keywordCriteria);
		}

		if ($this->payDateMin) {
			$criteria->compare('payDate', '>=' . $this->payDateMin);
		}
		if ($this->payDateMax) {
			$criteria->compare('payDate', '<=' . $this->payDateMax);
		}
		if ($this->priceMin) {
			$criteria->compare('price', '>=' . $this->priceMin);
		}
		if ($this->priceMax) {
			$criteria->compare('price', '<=' . $this->priceMax);
		}

		$criteria->compare('projectId', $this->projectId);

		$criteria->order = 'payDate DESC';

		return $criteria;
	}
}
